<template>
  <el-dialog
      id="homePreview"
      title="影像下载"
      :visible.sync="visible"
      v-loading="loading"
      :element-loading-text="loadingText"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      width="40%"
      top="15vh"
      center>
    <el-form ref="form" :model="form" label-width="100px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="导出类型" prop="exportType">
            <el-radio-group v-model="form.exportType">
              <el-radio label="T">TIF 格式</el-radio>
              <el-radio label="W">Web 格式</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item
              :label="form.exportType == 'T' ? 'TIF 名称' : '数据集名称'"
              prop="filename"
          >
            <el-input v-model="form.filename"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <template v-if="form.exportType == 'W'">
        <el-row>
          <el-col :span="12">
            <el-form-item label="最小缩放级别">
              <el-select v-model="form.minZoom" placeholder="请选择">
                <el-option
                    v-for="item in zoomList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    :disabled="item.value > form.maxZoom"
                >
                  <span>{{ item.label }} - {{ item.desc }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大缩放级别">
              <el-select v-model="form.maxZoom" placeholder="请选择">
                <el-option
                    v-for="item in zoomList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    :disabled="item.value < form.minZoom"
                >
                  <span>{{ item.label }} - {{ item.desc }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">返回</el-button>
      <el-button type="primary" @click="doExport">导出</el-button>
    </span>
  </el-dialog>
</template>
<script>
import {deleteTiles, generateTiles} from "@/api/geo";
import axios from "axios";

export default {
  name: 'TifExport',
  data() {
    return {
      visible: false,
      loading: false,
      loadingText: '',
      targetId : null,
      espgCode:null,
      form: {
        exportType: 'T',
        filename : '',
        minZoom : 6,
        maxZoom : 19
      },
      zoomList: [
        {
          label : 'Level 3',
          value : 3,
          desc : '19568 meters/pixel'
        },
        {
          label : 'Level 4',
          value : 4,
          desc : '9784 meters/pixel'
        },
        {
          label : 'Level 5',
          value : 5,
          desc : '4892 meters/pixel'
        },
        {
          label : 'Level 6',
          value : 6,
          desc : '2446 meters/pixel'
        },
        {
          label : 'Level 7',
          value : 7,
          desc : '1223 meters/pixel'
        },
        {
          label : 'Level 8',
          value : 8,
          desc : '611 meters/pixel'
        },
        {
          label : 'Level 9',
          value : 9,
          desc : '306 meters/pixel'
        },
        {
          label : 'Level 10',
          value : 10,
          desc : '153 meters/pixel'
        },
        {
          label : 'Level 11',
          value : 11,
          desc : '76 meters/pixel'
        },
        {
          label : 'Level 12',
          value : 12,
          desc : '38 meters/pixel'
        },
        {
          label : 'Level 13',
          value : 13,
          desc : '19 meters/pixel'
        },
        {
          label : 'Level 14',
          value : 14,
          desc : '9.6 meters/pixel'
        },
        {
          label : 'Level 15',
          value : 15,
          desc : '4.8 meters/pixel'
        },
        {
          label : 'Level 16',
          value : 16,
          desc : '2.4 meters/pixel'
        },
        {
          label : 'Level 17',
          value : 17,
          desc : '1.19 meters/pixel'
        },
        {
          label : 'Level 18',
          value : 18,
          desc : '0.60 meters/pixel'
        },
        {
          label : 'Level 19',
          value : 19,
          desc : '0.30 meters/pixel'
        },
          // 22层导出需要20分钟，19层目前是一个可观的层级
        {
          label : 'Level 20',
          value : 20,
          desc : '0.15 meters/pixel'
        },
        {
          label : 'Level 21',
          value : 21,
          desc : '0.07 meters/pixel'
        },
        {
          label : 'Level 22',
          value : 22,
          desc : '0.04 meters/pixel'
        },
        {
          label : 'Level 23',
          value : 23,
          desc : '0.02 meters/pixel'
        },
      ]
    }
  },
  created() {
    this.form.filename = '地理影像-' + this.generateRandom6DigitNumber();
  },
  methods: {
    generateRandom6DigitNumber() {
      // 生成一个 0 到 999999 之间的随机数
      const randomNumber = Math.floor(Math.random() * 1000000);
      // 补全 6 位，如果不足 6 位则在前面补 0
      return String(randomNumber).padStart(6, '0');
    },
    show(targetId,espgCode) {
      this.visible = true;
      this.targetId = targetId;
      this.espgCode=espgCode;
      // this.targetId = '96aa8c3d-2c66-49be-9fb5-642a17041a3e_affine';
    },
    resetTIF() {
      this.targetId = null;
    },
    doExport() {
      if(this.form.exportType === 'T') {
        const params = {
          affine_uuid: this.targetId,
          custom_filename: encodeURI(this.form.filename)
        };
        let queryString = new URLSearchParams(params).toString();
        window.location.href = `/api/downloadAffine_tif/?${queryString}`;
      }
      else if(this.form.exportType === 'W') {
        this.loading = true;
        this.loadingText = '切片生成中，这需要一点时间...';

        let preHandle;
        if(this.form.maxZoom > 19) {
          preHandle = deleteTiles(this.targetId);
        }
        else {
          preHandle = Promise.resolve();
        }

        preHandle.then(() => {
          generateTiles({
            "rawtif_uuid": this.targetId,
            "profile": "mercator",
            "zoom_levels": `${this.form.minZoom}-${this.form.maxZoom}`,
            "webviewer": "none",
            "espgCode": this.espgCode
          }).then(res => {
            const params = {
              uuid: this.targetId,
              min_level: this.form.minZoom,
              max_level: this.form.maxZoom,
              custom_filename: encodeURI(this.form.filename)
            };

            let queryString = new URLSearchParams(params).toString();
            this.downloadFile(`/api/downloadTiles_zip/?${queryString}`)
          }).catch(() => {
            this.loading = false;
          });
        }).catch(() => {
          this.loading = false;
        });
      }
    },
    downloadFile(url, fileName) {
      try {
        this.loadingText = '导出文件中';
        this.loading = true;
        axios.get(url, {
          responseType: 'blob',
          timeout: 600000
        }).then((response) => {
          if (!fileName) {
            const contentDisposition = response.headers['content-disposition'];
            if (contentDisposition && contentDisposition.includes('filename=')) {
              fileName = contentDisposition
                  .split('filename=')[1]
                  .split(';')[0]
                  .replace(/['"]/g, '');
            }
          }

          const blob = new Blob([response.data], {
            type: response.headers['content-type'],
          });

          const downloadUrl = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = downloadUrl;
          fileName = decodeURI(fileName);
          link.setAttribute('download', fileName || 'file'); // 设置下载文件名
          document.body.appendChild(link);

          link.click();

          window.URL.revokeObjectURL(downloadUrl);
          document.body.removeChild(link);
        }).finally(() => {
          this.loading = false;
        })
      } catch (error) {
        console.error('下载文件失败:', error);
      }
    }
  }
}
</script>
<style scoped lang="scss">

</style>
